// pages/handle/edit.js
var app = getApp();
var common = require('../../../service/common.js');
var gwang = require('../../../service/gwang.js');
var page_id = -1;
var ws_nav_id = -1;
var website_id = -1;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageContent: {},
    addModule: -1,
    DataList: [],
    num: 0,
    openid: -1,
    id: -1,
    ws_nav_id: -1
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showLoading({
      title: '加载中...',
    })
    var that = this;
    var pageContent = {};
    this.setData({
      openid: app.globalData.userInfo.openid,
      id: options.id
    })

    //*检查当前修改的是否与之前修改的为同一个*/
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log(wx.getStorageSync('DataList') == "")
    if (wx.getStorageSync('DataList') == "") {
      this.getPageContent(this.data.openid, this.data.id)
    } else {
      this.setData({
        DataList: wx.getStorageSync('DataList')
      })
      console.log(this.data.DataList)
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },


  onPullDownRefresh: function() {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },



  // 获取页面信息
  getPageContent: function(openid, id) {
    // app.globalData.userInfo.
    gwang.getPageContent(openid, id, res => {
      wx.hideLoading()
      
      for (var i in res.data.data.content) {
        if (res.data.data.content[i].lb_type == 1 || res.data.data.content[i].lb_type == 2) {
          res.data.data.content[i].height = 0
        }
      }
      wx.setStorageSync('DataList', res.data.data.content)
      this.setData({
        pageContent: res.data.data,
        DataList: res.data.data.content,
        num: 1,
        ws_nav_id: res.data.data.cur_nav.id
      })
    })
  },




  /*提升单个模块的排序*/
  upItemSort: function(e) {
    var that = this;
    var upItemIndex = e.currentTarget.dataset.sort; // 当前点击模块的sort
    wx.getStorage({
      key: 'pageContent',
      success: function(res) {
        var pageContent = res.data;
        for (var i = 0; i < pageContent.length; i++) {
          if (pageContent[i].sort < upItemIndex && pageContent[i].sort + 1 == upItemIndex) {
            // 如果当前的比选中的小，并且与之并排，将其序号 +1
            pageContent[i].sort++;
          } else if (pageContent[i].sort == upItemIndex) {
            // 将当前需要靠前排序的序号 -1
            pageContent[i].sort--;
          }
        }
        wx.setStorage({
          key: 'pageContent',
          data: pageContent,
        })
        that.setData({
          pageContent: pageContent
        })
        that.arraySort();
      },
    })
  },





  /*删除单个模块*/
  deleteItem: function(e) {
    this.data.DataList.splice(e.currentTarget.dataset.index, 1)
    wx.setStorageSync("DataList", this.data.DataList)
    this.setData({
      DataList: this.data.DataList
    })
    console.log(this.data.DataList)
  },



  /*将数据进行排序*/
  arraySort: function() {
    var that = this;
    var pageContent = {};
    wx.getStorage({
      key: 'pageContent',
      success: function(res) {
        pageContent = res.data;
        // 对比sort值将两个数据进行互换
        for (var i = 0; i < pageContent.length - 1; i++) {
          for (var j = 0; j < pageContent.length - 1 - i; j++) {
            if (pageContent[j].sort > pageContent[j + 1].sort) {
              var item = pageContent[j];
              pageContent[j] = pageContent[j + 1];
              pageContent[j + 1] = item;
            }
          }
        }

        wx.setStorage({
          key: 'pageContent',
          data: pageContent,
        })
        // 将排列好的数据setData
        that.setData({
          pageContent: pageContent
        })
      },
    })

  },


  /*点击弹出当前位置添加新模块的弹出框*/
  addItemModule: function(e) {
    this.setData({
      addModule: e.target.dataset.index
    })
  },
  // 更换图片
  tabImage: function(e) {
    this.upImage(e.currentTarget.dataset.index, e.currentTarget.dataset.inds)
  },
  // 上传图片
  upImage: function(index, inds) {
    wx.chooseImage({
      success: (res) => {
        var tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths)
        if (tempFilePaths.length > 0) {
          wx.showLoading({
            title: '上传中...',
          })
          wx.uploadFile({
            url: common.getUrl("website.uploadImg"),
            filePath: tempFilePaths[0],
            name: 'file',
            formData: {},
            success: (res) => {
              var data = JSON.parse(res.data)
              if (data.code == 0) {
                wx.hideLoading()
                this.data.DataList[index].content[inds] = data.data.url
                wx.setStorageSync("DataList", this.data.DataList)
                this.setData({
                  DataList: this.data.DataList
                })
              }
            }
          })
        }

      }
    })
  },
  /*点击遮罩层处取消添加*/
  addModuleCancle: function() {
    this.setData({
      addModule: -1
    })
  },

  /*添加标题*/
  addTitle: function(e) {
    console.log(e.currentTarget.dataset.index)
    wx.navigateTo({
      url: '/pages/addBox/addTitle/addTitle?index=' + e.currentTarget.dataset.index + "&edit=" + 2
    })
    this.setData({
      addModule: -1
    })
  },


  /*添加文本内容*/
  addContent: function(e) {
    wx.navigateTo({
      url: '/pages/addBox/addContent/addContent?index=' + e.currentTarget.dataset.index + "&edit=" + 2
    })
    this.setData({
      addModule: -1
    })
  },


  /*添加图片内容*/
  addImage: function(e) {
    wx.navigateTo({
      url: '/pages/addBox/addPicture/addPicture?index=' + e.currentTarget.dataset.index + "&type=" + 1
    })
    this.setData({
      addModule: -1
    })
    return
    wx.showActionSheet({
      itemList: ['横向轮播', '纵向轮播'],
      success: res => {
        console.log(res)
        if (res.tapIndex == 0) {
          wx.navigateTo({
            url: '/pages/addBox/addPicture/addPicture?index=' + e.currentTarget.dataset.index + "&type=" + 1
          })
          this.setData({
            addModule: -1
          })
        } else {
          wx.navigateTo({
            url: '/pages/addBox/zaddPicture/zaddPicture?index=' + e.currentTarget.dataset.index + "&type=" + 2
          })
          this.setData({
            addModule: -1
          })
        }
      }
    })

  },

  // 获取图片高度
  imageLoad: function(e) {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    var imgh = e.detail.height; //图片高度
    var imgw = e.detail.width; //图片宽度
    var swiperH = winWid * imgh / imgw
    console.log(swiperH)
    if (wx.getStorageSync('DataList') == "") {
      if (this.data.pageContent.content[e.target.dataset.index].height < swiperH) {
        this.data.pageContent.content[e.target.dataset.index].height = swiperH
      }
      this.setData({
        DataList: this.data.pageContent.content
      })
    } else {
      var data = wx.getStorageSync('DataList')
      if (data[e.target.dataset.index].height < swiperH) {
        data[e.target.dataset.index].height = swiperH
      }
      this.setData({
        DataList: data
      })
      wx.setStorageSync('DataList', data)
    }

  },
  /**添加视频内容 */
  addVideo: function(e) {
    wx.navigateTo({
      url: '/pages/addBox/addVideo/addVideo?index=' + e.currentTarget.dataset.index + "&edit=" + 2
    })
    this.setData({
      addModule: -1
    })
  },



  /*播放视频*/
  playVideo: function(e) {
    var filePath = e.currentTarget.dataset.video;
    wx.navigateTo({
      url: '/pages/addBox/play/play?filePath=' + filePath,
    })
  },


  /*添加单项整理数据*/
  addModuleFn: function(pageContent, content, sort, types, link) {

    var that = this;
    var array = {};

    if (types == "title") { /*数据类型为title*/
      array.types = 1;
      array.content = content;
      array.link = link;
      array.sort = sort;
      for (var i = 0; i < pageContent.length; i++) {
        if (pageContent[i].sort >= sort) {
          pageContent[i].sort++;
        }
      }
      pageContent.push(array);
      wx.setStorage({
        key: 'pageContent',
        data: pageContent
      })
      that.arraySort();
    }
    if (types == "content") { /*数据类型为content*/
      array.types = 2;
      array.content = content;
      array.link = link;
      array.sort = sort;
      for (var i = 0; i < pageContent.length; i++) {
        if (pageContent[i].sort >= sort) {
          pageContent[i].sort++;
        }
      }
      pageContent.push(array);
      that.setData({
        pageContent: pageContent
      })
      wx.setStorage({
        key: 'pageContent',
        data: pageContent
      })
      that.arraySort();
    }
    if (types == "image") { /*数据类型为image*/
      array.types = 3;
      content = content.split(',');
      console.log(content);
      array.content = content;
      array.link = link;
      array.sort = sort;
      for (var i = 0; i < pageContent.length; i++) {
        if (pageContent[i].sort >= sort) {
          pageContent[i].sort++;
        }
      }
      pageContent.push(array);
      that.setData({
        pageContent: pageContent
      })
      wx.setStorage({
        key: 'pageContent',
        data: pageContent
      })
      that.arraySort();
    }
    if (types == "video") { /*数据类型为video*/
      array.types = 4;
      array.content = content;
      array.link = link;
      array.sort = sort;
      for (var i = 0; i < pageContent.length; i++) {
        if (pageContent[i].sort >= sort) {
          pageContent[i].sort++;
        }
      }
      pageContent.push(array);
      that.setData({
        pageContent: pageContent
      })
      wx.setStorage({
        key: 'pageContent',
        data: pageContent
      })
      that.arraySort();
    }

  },




  /**修改单项整理数据 */
  editModuleFn: function(pageContent, content, sort, types, link) {
    console.log('我执行了单项修改')
    var that = this;
    var array = {};


    if (types == "title") { /*数据类型为title*/
      array.types = 1;
      array.content = content;
      array.link = link;
      array.sort = sort;
      for (var i = 0; i < pageContent.length; i++) {
        if (pageContent[i].sort == sort) {
          pageContent[i] = array;
        }
      }
      console.log(array);
      console.log(pageContent);
      wx.setStorage({
        key: 'pageContent',
        data: pageContent
      })
      that.arraySort();
    }
    if (types == "content") { /*数据类型为content*/
      array.types = 2;
      array.content = content;
      array.link = link;
      array.sort = sort;
      for (var i = 0; i < pageContent.length; i++) {
        if (pageContent[i].sort == sort) {
          pageContent[i] = array;
        }
      }
      that.setData({
        pageContent: pageContent
      })
      wx.setStorage({
        key: 'pageContent',
        data: pageContent
      })
      that.arraySort();
    }
    if (types == "image") { /*数据类型为image*/
      array.types = 3;
      content = content.split(',');
      array.content = content;
      array.link = link;
      array.sort = sort;
      console.log(array)
      for (var i = 0; i < pageContent.length; i++) {
        if (pageContent[i].sort == sort) {
          pageContent[i] = array;
        }
      }
      that.setData({
        pageContent: pageContent,
        testContent: pageContent
      });
      wx.setStorage({
        key: 'pageContent',
        data: pageContent
      })
    }
  },




  /*更换视频*/
  changeVideo: function(e) {
    var currentSort = e.currentTarget.dataset.sort;
    var that = this
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: function(res) {
        wx.showLoading({
          title: '上传中……',
        })
        that.setData({
          addModule: -1
        })
        var tempFilePath = res.tempFilePath;
        var thumbTempFilePath = res.thumbTempFilePath;
        wx.uploadFile({
          url: common.getUrl('webContent.uploadVideo'),
          filePath: tempFilePath,
          name: 'file',
          formData: {
            token: utils.getToken(app),
          },
          success: function(ret) {
            var ret = ret;
            wx.uploadFile({
              url: common.getUrl('webContent.uploadImg'),
              filePath: thumbTempFilePath,
              name: 'file',
              formData: {
                token: utils.getToken(app),
              },
              success: function(obj) {
                var Img = JSON.parse(obj.data);
                var res = JSON.parse(ret.data);
                if (res.code == 0) {
                  wx.hideLoading();
                  if (res.code == 0) {
                    var temp = {};
                    temp.url = res.data.url;
                    temp.img = Img.data.url;
                    wx.getStorage({
                      key: 'pageContent',
                      success: function(res) {
                        var pageContent = res.data;
                        for (var i = 0; i < pageContent.length; i++) {
                          if (pageContent[i].sort == currentSort) {
                            pageContent[i].content = temp;
                          }
                        }
                        wx.setStorage({
                          key: 'pageContent',
                          data: pageContent,
                        })
                        that.setData({
                          pageContent: pageContent
                        })
                      },
                    })

                  } else {
                    wx.showModal({
                      title: '提示',
                      content: res.message,
                    })
                  }
                }
              }
            })

          },
          fail: function(ret) {
            wx.hideLoading();
            var res = JSON.parse(ret.data);
            wx.showModal({
              title: '提示',
              content: res.message,
            })
          }
        })
      }
    })
  },



  /**更换图片 */
  changeImg: function(e) {
    var edit = e.currentTarget.dataset.sort
    wx.navigateTo({
      url: '/pages/addBox/addPicture/addPicture?edit=' + edit + '&page_id=' + page_id,
    })
  },


  /**更换标题 */
  editTitle: function(e) {

    wx.navigateTo({
      url: '/pages/addBox/addTitle/addTitle?inds=' + e.currentTarget.dataset.index + '&edit=' + 1,
    })
  },


  /**更换文本内容 */
  editContent: function(e) {
    wx.navigateTo({
      url: '/pages/addBox/addContent/addContent?inds=' + e.currentTarget.dataset.index + "&edit=" + 1,
    })
  },



  //*检查当前修改的是否与之前修改的为同一个*/
  presentEdit: function(id) {
    var that = this;
    wx.getStorage({
      key: 'page_id',
      success: function(res) {
        /*获取到当前本地缓存的 page_id，不相等替换掉 page_id，删除 pageContent的内容*/
        if (res.data != id) {
          wx.setStorage({
            key: 'page_id',
            data: id,
          })
          wx.removeStorage({
            key: 'pageContent',
            success: function(res) {
              console.log(res)
              /*重新获取页面内容*/
              that.getPageContent(0, id);
            }
          })
        } else {
          /*当前修改的为同一个页面的内容*/
        }
      },
      fail: function(res) {
        /**获取不到本地缓存的 page_id，添加 page_id，重新获取页面内容 */
        wx.setStorage({
          key: 'page_id',
          data: id,
        })
        that.getPageContent(0, id);
      }
    })
  },


  /**保存页面内容 */
  savePageContent: function() {
    wx.setStorageSync("DataList", "")
    gwang.saveContent(this.data.openid, this.data.id, this.data.DataList, this.data.ws_nav_id, (res) => {
      wx.showToast({
        title: '保存成功',
      })
      wx.navigateBack()
    })
  }
})